<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" pageEncoding="UTF-8" %>
<script>

    $(document).ready(function () {
        $.ajax({
            url: "${pageContext.request.contextPath}/user/findAllUser",
            method: "POST",
            async: true,
            success: function (data) {
                createUserList("#userList", data.users);
            }
        });
    });

    $("#userAdd").click(function () {
        window.location.href = "javascript:$('#content').load('./user/userManagerAdd.jsp')";
    });

    function userUpdate(id) {
        $("#userId").val(id);
        window.location.href = "javascript:$('#content').load('./user/userManagerUpdate.jsp')";
    }

    function delUser(id) {
        $.ajax({
            url: "${pageContext.request.contextPath}/user/delUser",
            method: "POST",
            data: {"id": id},
            async: true,
            success: function () {
                $.post("${pageContext.request.contextPath}/user/findAllUser", function (data) {
                    createUserList("#userList", data.users);
                })
            }
        });
    }

    function createUserList(selector, result) {
        $(selector).empty();
        if (result && result.length != 0) { //不为null,不为NaN,不为undefined
            $.each(result, function (index, user) {
                let c = "";
                $.each(user.roles, function (i, r) {
                    c += r.roleName + " ";
                });
                $(selector).append(`<tr><td>` + user.id + `</td><td>` + user.username + `</td><td>` + user.name + `</td><td>` + user.sex + `</td><td>` + user.age + `</td><td>` + c + `</td><td><button onclick='userUpdate("` + user.id + `")'>修改用户</button>&nbsp;&nbsp;<button onclick='delUser("` + user.id + `");'>删除用户</button></td></tr>`);
            });
        } else {//当值为空时
            $(selector).append("<tr><td colspan='7'>暂无数据</td></tr>");
        }
    }
</script>
<div class="col-sm-10">
    <div class="page-header">
        <h1>用户管理</h1>
    </div>
    <ul class="nav nav-tabs">
        <li class="active"><a href="#">用户信息</a></li>
    </ul>
    <table class="table table-striped">
        <thead>
        <tr>
            <td>ID</td>
            <td>用户名</td>
            <td>真实姓名</td>
            <td>性别</td>
            <td>年龄</td>
            <td>担任角色</td>
            <td>
                用户信息修改
            </td>
            <td>
                <button id="userAdd">用户添加</button>
            </td>
        </tr>
        </thead>
        <tbody id="userList"></tbody>
    </table>
</div>
